<template>
	<view class="cart-page">
		<view class="header">
			<text class="header-left">共 (<text style="color: red;">{{ total }}</text>)件</text>
			<text class="header-right" @click="toggleEditMode">{{ editMode ? '完成' : '管理' }}</text>
		</view>
		<scroll-view scroll-y class="cart-list" @scrolltolower="loadMore">
			<view v-for="item in cartItems" :key="item.id" class="cart-item">
				<view class="item-checkbox">
					<checkbox :value="item.id" v-model="item.checked" @click="toggleCheckbox(item.id)" />
				</view>
				<image :src="item.msqGoods.picture" class="item-image"></image>
				<view class="item-details">
					<text class="item-name">{{ item.msqGoodsAttrValue.sku }}</text>
					<text class="item-price">￥{{ item.msqGoodsAttrValue.price }}</text>
					<view class="goodsNum-controls">
						<button class="goodsNum-button" @click="decreasegoodsNum(item)">-</button>
						<text class="goodsNum-text">{{ item.goodsNum }}</text>
						<button class="goodsNum-button" @click="increasegoodsNum(item)">+</button>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="footer">
			<view v-if="editMode" class="footer-left">
				<checkbox v-model="selectAll" @click="toggleSelectAll">全选</checkbox>
			</view>
			<view v-if="!editMode" class="footer-left">
				<text>总计：￥{{ totalSelectedPrice }}</text>
			</view>
			<view class="footer-right">
				<button v-if="!editMode" class="buy-button" @click="checkout">立即购买</button>
				<button v-if="editMode" class="delete-button" @click="deleteSelected">删除</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getCartList,
		delCartList,
		editCreateOrder,
		postCreateOrder
	} from '@/api/order.js';
	export default {
		data() {
			return {
				cartItems: [],
				selectedItems: [], // 存储选中的商品
				editMode: false,
				selectAll: false,
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页大小
				total: '',
				totalPages: 0, // 总页数
				loading: false, // 加载状态
				noMoreData: false // 是否没有更多数据
			};
		},
		mounted() {
			this.getCartItems();
		},
		methods: {
			getCartItems(page = 1) {
				if (this.loading || this.noMoreData) return;
				this.loading = true;

				// 请求数据时传递当前页码和每页大小
				getCartList({
					pageNum: page,
					pageSize: this.pageSize
				}).then((res) => {
					console.log('Response data:', res.data); // 调试信息

					// 检查响应数据的格式
					if (res.data && Array.isArray(res.data.records)) {
						const newItems = res.data.records.map(item => ({
							id: item.id,
							msqGoods:item.msqGoods,
							msqGoodsAttrValue: item.msqGoodsAttrValue,
							checked: false,
							goodsNum: item.goodsNum || 1
						}));

						// 获取总页数
						this.totalPages = res.data.pages;
						this.total = res.data.total;

						// 根据当前页码决定如何处理新数据
						if (page === 1) {
							this.cartItems = newItems;
						} else {
							this.cartItems = [...this.cartItems, ...newItems];
						}

						this.loading = false;
						this.noMoreData = newItems.length < this.pageSize || this.currentPage >= this.totalPages;
					} else {
						console.error('Unexpected response format:', res.data);
						this.loading = false;
					}
				}).catch((error) => {
					console.error('Error fetching cart items:', error);
					this.loading = false;
				});
			},
			loadMore() {
				// 检查是否已经加载到最后一页
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
					this.getCartItems(this.currentPage);
				} else {
					this.noMoreData = true;
				}
			},
			toggleEditMode() {
				this.editMode = !this.editMode;
				if (!this.editMode) {
					this.selectAll = false;
					this.cartItems.forEach(item => item.checked = false);
				}
			},
			toggleCheckbox(id) {
				const item = this.cartItems.find(item => item.id === id);
				if (item) {
					item.checked = !item.checked;
					this.updateSelectedItems();
					this.updateSelectAll();
				}
			},
			toggleSelectAll() {
				this.selectAll = !this.selectAll;
				this.cartItems.forEach(item => {
					item.checked = this.selectAll;
				});
				this.updateSelectedItems();
			},
			updateSelectAll() {
				this.selectAll = this.cartItems.every(item => item.checked);
			},
			updateSelectedItems() {
				this.selectedItems = this.cartItems.filter(item => item.checked);
				console.log(this.selectedItems, "this.selectedItems");
			},
			checkout() {
				// 处理立即购买逻辑
				console.log('Checkout:', this.selectedItems);
				let array = {
					yhqId: null,
					tradeType:0,
					purchaseInformationVos: [{
						specificationId: this.selectedItems[0].msqGoods.id,
						buyCount: this.selectedItems[0].msqGoods.goodsPrice
					}]
				};
				postCreateOrder(array).then(res => {
					this.$util.Tips({
						title: "下单成功"
					});
				})
			},
			deleteSelected() {
				// 获取所有选中商品的ID
				const selectedIds = this.selectedItems.map(item => item.id);

				// 构建请求参数字符串
				const deleteParams = selectedIds.join(',');
				console.log(deleteParams, "deleteParams");

				// 调用删除接口
				delCartList(deleteParams).then(() => {
					// 删除成功后，更新本地数据
					this.cartItems = this.cartItems.filter(item => !item.checked);
					this.updateSelectedItems();
					this.selectAll = false;
					this.total = this.cartItems.length;
					console.log('Deleted successfully');
				}).catch((error) => {
					console.error('Error deleting cart items:', error);
				});
			},
			increasegoodsNum(item) {
				item.goodsNum += 1;
				const editArray = {
					id: item.id,
					goodsNum: item.goodsNum
				}
				editCreateOrder(editArray)
			},
			decreasegoodsNum(item) {
				if (item.goodsNum > 1) {
					item.goodsNum -= 1;
					const editArray = {
						id: item.id,
						goodsNum: item.goodsNum
					}
					editCreateOrder(editArray)
				}
			}
		},
		computed: {
			totalSelectedPrice() {
				return this.selectedItems.reduce((total, item) => total + (item.msqGoodsAttrValue.price * item.goodsNum),
					0);
			}
		}
	};
</script>

<style scoped>
	.cart-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		background-color: #f8f8f8;
		font-size: 18px;
	}

	.header-left,
	.header-right {
		cursor: pointer;
	}

	.cart-list {
		flex: 1;
		overflow-y: auto;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 10px;
		border-bottom: 1px solid #ccc;
	}

	.item-checkbox {
		margin-right: 10px;
	}

	.item-image {
		width: 80px;
		height: 80px;
		margin-right: 10px;
	}

	.item-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.item-name {
		font-size: 16px;
		margin-bottom: 5px;
	}

	.item-price {
		color: red;
		font-size: 14px;
		margin-bottom: 10px;
	}

	.goodsNum-controls {
		display: flex;
		align-items: center;
	}

	.goodsNum-button {
		width: 30px;
		height: 30px;
		border: 1px solid #ccc;
		background-color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.goodsNum-text {
		margin: 0 10px;
		font-size: 14px;
	}

	.footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		background-color: #f8f8f8;
		box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
	}

	.footer-left,
	.footer-right {
		display: flex;
		align-items: center;
	}

	.buy-button,
	.delete-button {
		width: 140px;
		height: 40px;
		border-radius: 40rpx;
		line-height: 20px;
		background-color: #085CD6;
		color: white;
		padding: 10px 20px;
		border: none;
		cursor: pointer;
	}

	.delete-button {
		background-color: #085CD6;
	}
</style>